package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.service.impl.ApplicationInfoServiceImpl;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoHuiTuiUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaAESUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaApibUtil;
import com.block.datapush.service.apipush.utils.YinXiaoHuaApibUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 银小花全国
 */
@Service
public class YinXiaoHuaApiBRatePushService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    DataMatchOrderItemMapper dataMatchOrderItemMapper;
    @Autowired
    ApplicationInfoServiceImpl applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:2);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("loanAmount", YinXiaoHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTime", YinXiaoHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("education", YinXiaoHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("occupation", YinXiaoHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        Integer i = YinXiaoHuaApibUtil.getShangBan1(memberSourceInfo.getGongzuo());
        if(i > 0){
            paramMap.put("companyMoney",3);
            paramMap.put("companyTime",2);
        }
        paramMap.put("socialInsurance", YinXiaoHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("houseFund", YinXiaoHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("car", YinXiaoHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YinXiaoHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        Integer house = YinXiaoHuaApibUtil.getHouse(memberSourceInfo.getHouse());
        if(house < 3){
            paramMap.put("houseType", 4);
        }

        paramMap.put("lifeInsurance", YinXiaoHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("creditCard",YinXiaoHuaApibUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("zhimaScore", YinXiaoHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("overdue", YinXiaoHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));

        String encrypt = encrypt(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        aceMap.put("timestamp",timeStamp);
        aceMap.put("channel",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);
        aceMap.put("sign",sign(timeStamp,pushApiKeyParam.getApiCode(),encrypt,pushApiKeyParam.getApiKey()));


        log.info("【银小花半流程分润】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【银小花半流程分润】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            JSONObject data = resultObject.getJSONObject("data");
            String serialNo = data.getString("serialNo");
            pushApiResult.setOutOrderNo(mobileMd5);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setSettleFlag(true);
            pushApiResult.setPushSuccess(true);
            extJson.put("outOrderNo",serialNo);
            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = data.getBigDecimal("price");
                if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }

        return pushApiResult;
    }



    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneNo", memberSourceInfo.getMobile());
        String serialNo = extJson.getString("outOrderNo");
        paramMap.put("serialNo",serialNo);
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1? 1:2);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("loanAmount", YinXiaoHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTime", YinXiaoHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("education", YinXiaoHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("occupation", YinXiaoHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        Integer i = YinXiaoHuaApibUtil.getShangBan1(memberSourceInfo.getGongzuo());
        if(i > 0){
            paramMap.put("companyMoney",3);
            paramMap.put("companyTime",2);
        }
        paramMap.put("socialInsurance", YinXiaoHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("houseFund", YinXiaoHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("car", YinXiaoHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YinXiaoHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        Integer house = YinXiaoHuaApibUtil.getHouse(memberSourceInfo.getHouse());
        if(house < 3){
            paramMap.put("houseType", 4);
        }
        paramMap.put("lifeInsurance", YinXiaoHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("creditCard",YinXiaoHuaApibUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("zhimaScore", YinXiaoHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("overdue", YinXiaoHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/xiaocaiprotocol/{}.html", appInfoByAppCode.getApiUrl(), memberSourceInfo.getUid());
        paramMap.put("protocolUrl", protocolUrl);
        paramMap.put("protocolTime", new Date());

        String encrypt = encrypt(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        String timeStamp = String.valueOf(System.currentTimeMillis());
        aceMap.put("timestamp",timeStamp);
        aceMap.put("channel",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);
        aceMap.put("sign",sign(timeStamp,pushApiKeyParam.getApiCode(),encrypt,pushApiKeyParam.getApiKey()));
        log.info("【银小花半流程分润】导单开始【requestUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【银小花半流程分润】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(aceMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            String url = data.getString("url");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String phoneMd5 = jsonObject.getString("md5");
        noticeParamDTO.setOrderNo(phoneMd5);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


    public static String sign(String timeStamp, String channelCode,String text,String secret) {
        try {
            String stringToSign = channelCode+"&"+text+"&"+timeStamp+secret;
            return md5(stringToSign);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }

    private static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        return bytesToHex(messageDigest);
    }

    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString().toLowerCase();
    }


    /**
     * 加密
     *
     * @param input 输入
     * @param aesKey   关键
     * @return {@code String}
     */
    public static String encrypt(String input, String aesKey) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes("UTF-8"));
        } catch (Exception e) {
            log.error("aes加密错误，原因是：", e);
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(crypted);
    }


}
